/*
 * @Description: 拆分案卷弹窗
 * @Author: Rfan
 * @Date: 2022-07-18 15:02:39
 * @LastEditTime: 2022-07-18 16:02:39
 */

import { useState } from 'react';
import { Button, Checkbox, Divider, Form, Input, Popover, Space, Typography } from 'antd';
import classNames from 'classnames/bind';
import { useLevelTableContext } from '../../contexts/LevelTableContext';
import type { IMetadata } from '@/interfaces/metadata';
import styles from '../../styles/levelTable.module.scss';

const cx = classNames.bind(styles);

const FilterBtn = () => {
  const { filterFields, baseInfo, setListQuery } = useLevelTableContext();
  const [form] = Form.useForm();

  const [filterOpen, setFilterOpen] = useState(false);
  const [getNullFlag, setGetNullFlag] = useState(false);

  const hidePopover = () => {
    setFilterOpen(false);
  };

  const submitFilter = () => {
    form.submit();
  };

  // 过滤条件
  const onFinish = (values: any) => {
    const blankItemFlag = getNullFlag ? 1 : 0;
    const filters = Object.entries(values)
      .map(([fieldName, fieldValue]) => ({
        fieldName,
        fieldValue
      }))
      .filter((item) => item.fieldValue !== undefined);

    setListQuery({
      pageNo: 1,
      pageSize: 10,
      param: { ...baseInfo.param, blankItemFlag, filters }
    });
    hidePopover();
  };

  const filterContent = (
    <div>
      <div>
        <Checkbox
          checked={getNullFlag}
          onChange={(evt) => {
            setGetNullFlag(evt.target.checked);
          }}
        >
          提取空条目
        </Checkbox>
        <Typography.Paragraph type="secondary">
          提取不完整的条目，对不完整档案补充著录
        </Typography.Paragraph>
      </div>
      <Divider />
      <Form
        form={form}
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 14 }}
        size="small"
        onFinish={onFinish}
      >
        {filterFields.map((field: IMetadata) => (
          <Form.Item key={field.field_name} label={field.field_desc} name={field.field_name}>
            <Input />
          </Form.Item>
        ))}
      </Form>
      <Space className={cx('filter-operate')}>
        <Button
          size="small"
          onClick={() => {
            submitFilter();
          }}
        >
          确定
        </Button>
      </Space>
    </div>
  );

  return (
    <>
      <Popover
        content={filterContent}
        title="筛选条件"
        placement="bottomRight"
        trigger="click"
        visible={filterOpen}
        onVisibleChange={setFilterOpen}
      >
        <Button>筛选</Button>
      </Popover>
    </>
  );
};

export default FilterBtn;
